﻿using System;
using System.ComponentModel;
using System.Data;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Threading;
using System.Configuration;

namespace SqlProcessViewer
{
	/// <summary>
	/// Interaction logic for MainWindow.xaml
	/// </summary>
	public partial class MainWindow : Window
	{
		#region Constants

		private const string APPSETTING_REFRESH = "RefreshIntervalInSeconds";
		private const string PROCESS_SP = "sp_who2";

		#endregion

		#region Variables

		private int _refreshIntervalInSeconds;
		private GridViewColumnHeader _lastHeaderClicked;
		private ListSortDirection _lastDirection;
		private DispatcherTimer _refreshTimer;

		#endregion

		#region Constructors

		public MainWindow()
		{
			InitializeComponent();
			_refreshIntervalInSeconds = Convert.ToInt32(ConfigurationManager.AppSettings[APPSETTING_REFRESH]);
			_lastHeaderClicked = null;
			_lastDirection = ListSortDirection.Ascending;
			Results = new DatabaseReader(CommandType.StoredProcedure, PROCESS_SP);
			_refreshTimer = new DispatcherTimer(
				new TimeSpan(0, 0, _refreshIntervalInSeconds),
				DispatcherPriority.Normal,
				(sender, e) => Results.Refresh(),
				Dispatcher);
			_refreshTimer.Start();
		}

		#endregion

		#region Properties

		private DatabaseReader Results
		{
			get
			{
				return DataContext as DatabaseReader;
			}
			set
			{
				DataContext = value;
			}
		}

		#endregion

		#region Methods

		private void Sort(string sortBy, ListSortDirection direction)
		{
			var dataView = CollectionViewSource.GetDefaultView(Results);
			dataView.SortDescriptions.Clear();
			dataView.SortDescriptions.Add(new SortDescription(sortBy, direction));
			dataView.Refresh();
		}

		#endregion

		#region Event Handlers

		private void RefreshCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
		{
			Results.Refresh();
		}

		private void ColumnHeader_Clicked(object sender, RoutedEventArgs e)
		{
			var headerClicked = e.OriginalSource as GridViewColumnHeader;
			var direction = ListSortDirection.Ascending;

			if ((headerClicked != null) && (headerClicked.Role != GridViewColumnHeaderRole.Padding))
			{
				direction = (headerClicked == _lastHeaderClicked) ? _lastDirection.Toggle() : ListSortDirection.Ascending;
				Sort(headerClicked.Column.Header.ToString(), direction);
				headerClicked.Column.HeaderTemplate = Resources[direction.ToResourceName()] as DataTemplate;

				// Remove arrow from previously sorted header:
				if ((_lastHeaderClicked != null) && (_lastHeaderClicked != headerClicked))
				{
					_lastHeaderClicked.Column.HeaderTemplate = null;
				}

				_lastHeaderClicked = headerClicked;
				_lastDirection = direction;
			}
		}

		#endregion
	}
}